package com.derbysoft.dswitch.adapter.ihg.dswitch2.translate;

import com.derbysoft.dswitch.adapter.ihg.dswitch3.translate.Translator;
import com.derbysoft.remote.dswitch.core.GenericRQ;
import com.derbysoft.remote.dswitch.core.RequestHeader;
import com.derbysoft.remote.dswitch.generic.constants.AgeQualifyingType;
import com.derbysoft.remote.dswitch.hotel.dto.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.SerializationUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("ds2HotelMultiAvailRQTranslator")
public class HotelMultiAvailRQTranslator
        implements Translator<GenericRQ<HotelMultiAvailRQ>, List<GenericRQ<HotelAvailRQ>>,Void> {

    public List<GenericRQ<HotelAvailRQ>> translate(GenericRQ<HotelMultiAvailRQ> hotelMultiAvailRQ,Void o) {
        List<GenericRQ<HotelAvailRQ>> hotelAvailRQs = new ArrayList<GenericRQ<HotelAvailRQ>>();
        for (HotelRefDTO hotel : hotelMultiAvailRQ.getPayload().getHotels()) {
            GenericRQ<HotelAvailRQ> hotelAvailRQ = new GenericRQ<HotelAvailRQ>();
            hotelAvailRQ.setHeader((RequestHeader) SerializationUtils.clone(hotelMultiAvailRQ.getHeader()));
            HotelAvailRQ payLoad = new HotelAvailRQ();
            payLoad.setAvailCriteria(translateHotelVailCriteria(hotelMultiAvailRQ, hotel));
            hotelAvailRQ.setPayload(payLoad);
            hotelAvailRQs.add(hotelAvailRQ);
        }
        return hotelAvailRQs;
    }

    private HotelAvailCriteriaDTO translateHotelVailCriteria(GenericRQ<HotelMultiAvailRQ> hotelMultiAvailRQ, HotelRefDTO hotel) {
        HotelAvailCriteriaDTO availCriteria = new HotelAvailCriteriaDTO();
        availCriteria.setHotelRef((HotelRefDTO) SerializationUtils.clone(hotel));
        availCriteria.setLanguageType(hotelMultiAvailRQ.getPayload().getLanguageType());
        availCriteria.setRoomStayCandidates(
                (RoomStayCandidateDTO) SerializationUtils.clone(hotelMultiAvailRQ.getPayload().getRoomStayCandidates())
        );
        appendChildGuest(availCriteria);
        availCriteria.setStayDateRange((StayDateRangeDTO) SerializationUtils.clone(hotelMultiAvailRQ.getPayload().getStayDateRange()));
        return availCriteria;
    }

    private void appendChildGuest(HotelAvailCriteriaDTO availCriteria) {
        List<GuestCountDTO> guestCounts = availCriteria.getRoomStayCandidates().getGuestCounts();
        Object childFound = CollectionUtils.find(guestCounts, new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                GuestCountDTO each = (GuestCountDTO) object;
                return AgeQualifyingType.CHILD == each.getAgeQualifyingType();
            }
        });
        if (childFound == null) {
            guestCounts.add(new GuestCountDTO(AgeQualifyingType.CHILD, 0));
        }
    }
}

